package com.yimi.yinhepda.views.unload_module;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.pda.ym.db.table.UnloadScanTable;
import com.yimi.yinhepda.R;
import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.db.dao.LoadUnloadGroupTableDao;
import com.yimi.yinhepda.db.dao.ScanDetailVoDao;
import com.yimi.yinhepda.db.dao.UnloadScanTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.entity.bean.TaskEntity;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.FastClick;
import com.yimi.yinhepda.views.load_module.LoadUnloadGroupActivity;
import com.yimi.yinhepda.views.offline.unload.OffLineUnloadActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 任务暂存集界面
 *
 * @author 000432
 */
public class TaskCashCollectionActivity extends BaseActivity {
    private ListView listView;
    private TaskCashAdapter adapter;
    private TextView num;
    //卸车标志
    private int operTypeCode = 4;

    private UnloadTaskTableDao mUnloadTaskTableDao;
    private UnloadScanTableDao mUnloadScanTableDao;
    private List<TaskEntity> listTaskEntity = new ArrayList<TaskEntity>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_cash_collection);
        initView();
        initData();
    }

    @Override
    public String getPageName() {
        return "任务暂存集";
    }

    public void initView() {
        ((TextView) findViewById(R.id.title)).setText("任务暂存集");
        num = (TextView) findViewById(R.id.num);
        listView = (ListView) findViewById(R.id.unload_task_cash_listview);
        findViewById(R.id.unload_task_cash_btn_back).setOnClickListener(this);
        findViewById(R.id.unload_task_cash_btn_del).setOnClickListener(this);
        findViewById(R.id.unload_task_cash_btn_exec).setOnClickListener(this);
    }

    private void initData() {
        mUnloadTaskTableDao = new UnloadTaskTableDao();
        mUnloadScanTableDao = new UnloadScanTableDao();
        //设置未上传数
        num.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode) + "");

        //查询暂存的配置单号
        List<UnloadTaskTable> listUnloadTaskTable = mUnloadTaskTableDao.findUnComplete(0, sharedPreferUtil.getValue(Common.USER_CODE));
        if (listUnloadTaskTable != null && listUnloadTaskTable.size() > 0) {
            for (UnloadTaskTable item : listUnloadTaskTable) {
                if (item.getOfflineTaskNo() != null) {
                    if (item.getOfflineTaskNo().startsWith("Z") || item.getOfflineTaskNo().startsWith("X")) {
                        continue;
                    }
                }
                boolean isExist = false;
                for (TaskEntity temp : listTaskEntity) {
                    if (temp.getTask() != null && item.getTask() != null) {
                        if (temp.getTask().equals(item.getTask())) {
                            isExist = true;
                            if (!temp.getCarNo().contains(item.getCarNo())) {
                                temp.setCarNo(temp.getCarNo() + "/" + item.getCarNo());
                            }
                            temp.setPriceNum(temp.getPriceNum() + item.getPriceNum());
                            if (!temp.getSrcDeptName().contains(item.getSrcDeptName())) {
                                temp.setSrcDeptName(temp.getSrcDeptName() + "/" + item.getSrcDeptName());
                            }
                        }
                    }
                }
                if (!isExist) {
                    listTaskEntity.add(new TaskEntity(item.getTask(), item.getStowageNo(), item.getCarMark(), item.getToCompCode(), item.getSrcDeptCode(), item.getSrcDeptName(),
                            item.getDestDeptCode(), item.getDestDeptName(), item.getCarNo(), item.getPriceNum(), false));
                }
            }
        }

        adapter = new TaskCashAdapter(this, listTaskEntity);
        listView.setAdapter(adapter);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        //防抖
        if (FastClick.isFastClick()) {
            return;
        }

        switch (v.getId()) {
            case R.id.unload_task_cash_btn_back:
                finish();
                break;
            case R.id.unload_task_cash_btn_del:
                //删除按钮
                if (listTaskEntity != null && listTaskEntity.size() > 0) {
                    int i = adapter.getCheck();
                    if (i == -1) {
                        showToast("请先选中要删除的项！");
                        return;
                    }
                    TaskEntity mTaskEntity = listTaskEntity.get(i);
                    try {
                        //删除任务表和扫描表
                        UnloadTaskTableDao mUnloadTaskTableDao = new UnloadTaskTableDao();
                        List<UnloadTaskTable> list = mUnloadTaskTableDao.findData(mTaskEntity.getTask());
                        mUnloadTaskTableDao.delete(list);

                        UnloadScanTableDao mUnloadScanTableDao = new UnloadScanTableDao();
                        List<UnloadScanTable> listTemp = mUnloadScanTableDao.getTaskData(mTaskEntity.getTask());
                        if (listTemp != null && listTemp.size() > 0) {
                            mUnloadScanTableDao.delete(listTemp);
                        }

                        //根据配载单删除
                        String stowageNo = mTaskEntity.getStowageNo();
                        mUnloadScanTableDao.deleteByTaskNo(stowageNo);
                        new ScanDetailVoDao().deleteByTaskNo(stowageNo);
                        mUnloadTaskTableDao.deleteByTaskNo(stowageNo);
                        //删除暂存的装卸人
                        LoadUnloadGroupTableDao loadUnloadGroupTableDao = new LoadUnloadGroupTableDao();
                        loadUnloadGroupTableDao.delete(loadUnloadGroupTableDao.getDataByTask(mTaskEntity.getTask()));

                        listTaskEntity.remove(i);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    adapter.notifyDataSetChanged();
                }
                //设置未上传数
                num.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode) + "");
                break;
            case R.id.unload_task_cash_btn_exec:
                //执行按钮
                if (listTaskEntity != null && listTaskEntity.size() > 0) {
                    int i = adapter.getCheck();
                    if (i == -1) {
                        showToast("请先选中要执行的项！");
                        return;
                    }
                    TaskEntity mTaskEntity = listTaskEntity.get(i);
                    if (mTaskEntity.getStowageNo().startsWith("P") || !mTaskEntity.getStowageNo().startsWith("X")) {
                        //快运 或者 非离线卸车配载单
                        Intent unloadScanIntent = null;
                        Bundle bundle = new Bundle();
                        int deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
                        if (deptType == 5 || deptType == 6) {
                            if (!sharedPreferUtil.getBooleanValue(Common.HAS_UNLOAD_GROUP)) {
                                //没有装卸组信息跳转至装卸组重新获取装卸人员
                                unloadScanIntent = new Intent(TaskCashCollectionActivity.this, LoadUnloadGroupActivity.class);
                                //扫描类型：1-装车扫描，2-卸车扫描
                                bundle.putInt("scanType", 2);
                            } else {
                                unloadScanIntent = new Intent(TaskCashCollectionActivity.this, UnloadScanActivity.class);
                            }
                        } else {
                            unloadScanIntent = new Intent(TaskCashCollectionActivity.this, UnloadScanActivity.class);
                        }

                        //unloadScanIntent = new Intent(TaskCashCollectionActivity.this, UnloadScanActivity.class);


                        bundle.putString("carNo", mTaskEntity.getCarNo());
                        bundle.putString("task", mTaskEntity.getTask());
                        bundle.putString("deptCode", mTaskEntity.getSrcDeptName());
                        List<String> currentDeptCodes = new ArrayList<>();
                        currentDeptCodes.add(mTaskEntity.getDestDeptCode());
                        bundle.putSerializable("currentDeptCodes", (Serializable) currentDeptCodes);
                        unloadScanIntent.putExtras(bundle);
                        startActivity(unloadScanIntent);
                    } else if (mTaskEntity.getStowageNo().startsWith("X")) {
                        //离线卸车
                        Intent unloadScanIntent = new Intent(TaskCashCollectionActivity.this, OffLineUnloadActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("stowageNo", mTaskEntity.getStowageNo());
                        bundle.putString("deptCode", mTaskEntity.getSrcDeptCode());
                        bundle.putString("deptName", mTaskEntity.getSrcDeptName());
                        //选择的上一站code
                        bundle.putString("preCompany", mTaskEntity.getPreCompanyCode());
                        unloadScanIntent.putExtras(bundle);
                        startActivity(unloadScanIntent);
                    }

                    finish();
                }
                break;
            default:
                break;
        }
    }
}

class TaskCashAdapter extends BaseAdapter {
    private List<TaskEntity> dataList;
    private Context context;

    public TaskCashAdapter(Context context, List<TaskEntity> dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    public int getCheck() {
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).isChecked()) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public int getCount() {
        return null == dataList ? 0 : dataList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final MyHolder myHolder;
        if (convertView == null) {
            myHolder = new MyHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.taskcashcollection_listview_item, null);
            myHolder.linearLayout = (LinearLayout) convertView.findViewById(R.id.task_item_layout);
            myHolder.carCode = (TextView) convertView.findViewById(R.id.taskCash_btn_CarCode);
            myHolder.deptCode = (TextView) convertView.findViewById(R.id.taskCash_btn_DeptCode);
            myHolder.carNo = (TextView) convertView.findViewById(R.id.taskCash_btn_CarNo);
            myHolder.priceNum = (TextView) convertView.findViewById(R.id.taskCash_btn_pricenum);
            myHolder.radioButton = (RadioButton) convertView.findViewById(R.id.taskCash_radiobtn);
            convertView.setTag(myHolder);
        } else {
            myHolder = (MyHolder) convertView.getTag();
        }
        TaskEntity taskEntity = dataList.get(position);
        if (!taskEntity.getStowageNo().startsWith("P")) {
            myHolder.carCode.setText(taskEntity.getCarMark());
        } else {
            myHolder.carCode.setText(taskEntity.getStowageNo());
        }
        myHolder.deptCode.setText(dataList.get(position).getSrcDeptName());
        myHolder.carNo.setText(dataList.get(position).getCarNo());
        myHolder.priceNum.setText(dataList.get(position).getPriceNum() + "");
        if (dataList.get(position).isChecked()) {
            myHolder.radioButton.setChecked(true);
        } else {
            myHolder.radioButton.setChecked(false);
        }

        myHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
            int index = position;

            @Override
            public void onClick(View v) {
                //设置其他的不选中
                for (TaskEntity item : dataList) {
                    item.setChecked(false);
                }
                dataList.get(index).setChecked(true);
                notifyDataSetChanged();
            }
        });

        myHolder.radioButton.setOnClickListener(new View.OnClickListener() {
            int index = position;

            @Override
            public void onClick(View v) {
                //设置其他的不选中
                for (TaskEntity item : dataList) {
                    item.setChecked(false);
                }
                dataList.get(index).setChecked(true);
                notifyDataSetChanged();
            }
        });
        return convertView;
    }
}

class MyHolder {
    LinearLayout linearLayout;
    TextView carCode;
    TextView deptCode;
    TextView carNo;
    TextView priceNum;
    RadioButton radioButton;
}
